<template>
  <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
      </van-list>
  </div>
</template>

<script>
import { getSearchResults } from '@/api/search.js'
export default {
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 加载状态结束
      finished: false,
      page: 1,
      error: false
    }
  },

  created () {

  },

  methods: {
    // 1.list列表第一次显示
    // 2.数据没有显示一整屏
    // 3.上拉触底
    async onLoad () {
      try {
        // 1.发送请求
        const res = await getSearchResults({
          page: this.page,
          pre_page: 10,
          q: this.searchText
        })
        if (Math.random() > 0.5) {
          console.lg(1)
        }
        this.page++
        console.log(res)
        // 2.保存数据
        this.list.push(...res.results)
        // 3.当前加载状态结束
        this.loading = false
        // 4.数据全部加载完成(控制是否还加载下一页)
        if (this.list.length >= res.total_count) {
          this.finished = true
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    }
  }
}
</script>

<style scoped>

</style>
